package cn.itcast.dewu.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.itcast.dewu.dto.UserDTO;
import cn.itcast.dewu.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static cn.itcast.dewu.utils.RedisConstants.LOGIN_USER_KEY;
import static cn.itcast.dewu.utils.RedisConstants.LOGIN_USER_TTL;

public class TokenRefushInterceptor implements HandlerInterceptor {

    private StringRedisTemplate redisTemplate;

    public TokenRefushInterceptor(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
     //获取请求头中的token
        String token = request.getHeader("authorization");
        if (StrUtil.isEmpty(token)) {
            return true;
        }
        //获取到userdto信息
        Map<Object, Object> userDtoMap = redisTemplate.opsForHash().entries(LOGIN_USER_KEY + token);
        if (userDtoMap.isEmpty()) {
            return true;
        }
        //将查询的userDtoMap转换成userdto
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userDtoMap, new UserDTO(), false);
        UserHolder.saveUser(userDTO);//将userdtto加入到threaLocal
        //刷新一下有效期
        redisTemplate.expire(LOGIN_USER_KEY + token, LOGIN_USER_TTL, TimeUnit.MINUTES);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
